# Laura Lemay's Web Workshop

# JavaScript

### by Laura Lemay and Michael G. Moncur

## C O N T E N T S

## Introduction

## Chapter 1 Creating Simple JavaScript Programs

- What Is JavaScript?
  - History of JavaScript
- JavaScript Versus Java
- Combining JavaScript with HTML
  - Simplified Language Structure
  - Web Browser Integration
  - Supported on More Platforms
- Uses for JavaScript
  - Including Dynamic Information
  - Validating Forms
  - Making Pages Interactive
- Getting Started with JavaScript
  - Required Software and Hardware
  - Development Tools
- Testing a Simple JavaScript Program
  - Receiving the Web Page
  - Procssing the Script
- Potential Problems with JavaScript
  - Security Considerations
  - Your Source Code Is Accessible
- Overcoming JavaScript's Limitations
  - Missing Features
  - Combining JavaScript with Other Languages
- Writing a Simple JavaScript Application
  - Creating the Script
  - Embedding the Script in an HTML Page
- Creating an Event Handler
  - Viewing Your Script's Output
- Hiding JavaScript from Older Browsers
- Workshop Wrap-Up
  - Next Steps
  - Q&A

## Chapter 2 Working with Larger Programs and Variables

- JavaScript Language Structure
  - Statements
  - Functions
  - Variables
  - Expressions
  - Objects, Properties, and Methods
- Using Comments
- Programs and Applications
- Data Types and Variables
  - Integers
  - Floating-Point Numbers
  - Boolean Values
  - Strings
  - Special Characters
- Creating an Array
- Working with Numbers and Text
- Naming and Declaring Variables
  - Rules for JavaScript Variable Names
- Assigning Values to Variables
- Variable Declarations and Scope
- Declaring Variables
- Using Expressions and Operators
  - Assignment Operators
  - Arithmetic Operators
- Incrementing and Decrementing Variables
  - String Operators
  - Logical Operators
  - Bitwise Operators
  - Comparison Operators
  - Understanding Operator Precedence
- Using Variables in Expressions
- Converting and Evaluating Variables and Expressions
  - The `parseInt` Function
  - The `parseFloat` Function
  - The `eval` Function
- Workshop Wrap-Up
  - Next Steps
  - Q&A

## Chapter 3 Working with Objects and Events

- Using JavaScript Objects
- Using Object Properties
  - Assigning Values to Properties
- Functions and Methods
- Declaring a Function
  - Calling a Function
  - Returning a Value
  - Integrating Functions with HTML
  - Dividing a Task into Functions
  - Communication Between Functions
- Understanding Methods
- Defining Objects and Methods
- Creating Instances of Objects
  - Putting It All Together
- Conditionals and Loops
  - The `if...else` Construct
  - Conditional Expressions
- Using the `for` Keyword
- Using `while` Loops
  - The `for...in` Construct
  - Infinite Loops
  - The `break` Statement
  - The `continue` Statement
- Using Multiple Parameters in Functions
- Events and Event Handlers
  - Types of Events
- Creating an Event Handler
  - How Event Handlers Interact
- Workshop Wrap-Up
  - Next Steps
  - Q&A

## Chapter 4 Using Built-In Objects and Custom Objects

- Techniques for Object-Oriented Programming
- Using Objects, Properties, and Methods
  - The `new` Keyword
  - The `this` Keyword
  - The `with` Keyword
  - Creating a Generic Object
- Looping Through an Object's Properties
- Using Built-In Objects
  - Using `Array` Objects
- Creating an Array
  - Using `String` Objects
  - Using `Date` Objects
  - The `Math` Object
  - The `navigator` Object
- Customizing Objects
- Customizing the `String` Object
- Workshop Wrap-Up
  - Next Steps
  - Q&A

## Chapter 5 Accessing Window Elements as Objects

- The `window` Object
  - `window` Object Properties
- Changing the Status Line
  - `window` Object Methods
- Opening and Closing Windows
- Using Prompts, Alerts, and Confirmation Dialogs
- Updating a Page with Timeouts
- Using `window` Object Event Handlers
- The `location` Object
- The `document` Object
  - `document` Object Properties
  - `document` Object Methods
- The `history` Object
- Implementing BACK and FORWARD Buttons
- The `link` Object
- The `anchor` Object
- `form` Objects
- Workshop Wrap-Up
  - Next Steps
  - Q&A

## Chapter 6 Using Interactive Forms

- Building a JavaScript-Compatible HTML Form
  - Understanding Form Actions and Methods
  - Overview of Form Elements
- Creating an HTML Form
- Using `form` Objects in JavaScript
  - `form` Object Properties
  - `form` Object Methods and Events
- The JavaScript `form` Object Hierarchy
  - Text Fields and Password Fields
  - Text Areas
  - Checkboxes
  - Radio Buttons
  - Selection Lists
  - Hidden Fields
  - Buttons
  - File Upload Fields
- Automating the Form with JavaScript
- Adding Automatic Totals
- Automating the Shipping Address
- Validating the Form Data with Event Handlers
  - Where to Validate?
  - Which Fields to Validate?
- Creating Functions for Validation
- Adding an Event Handler for Validation
- Workshop Wrap-Up
  - Next Steps
  - Q&A

## Chapter 7 Real-Life Examples I

- Example 1: Displaying a Pop-Up Message
- Example 2: Displaying Random Quotations
- Example 3: A Validated Registration Form

## Chapter 8 Improving a Web Page with JavaScript

- The Beginning: A Simple Web Page
  - The Main Page
- Creating a Navigation Bar
  - Naming the Pages
- Creating the Data Structures and HTML for the Navigation Bar
- Creating the Function for the Navigation Bar
- Integrating the Navigation Bar with the HTML Page
- Using the Status Line
- Creating Friendly Links
- Adding a Scrolling Message
- Using a Text Field to Scroll a Message
- Workshop Wrap-Up
  - Next Steps
  - Q&A

## Chapter 9 Using Frames, Cookies, and Other Advanced Features

- Advanced Browser Features
  - Frames
  - Targeted Links
  - Cookies
  - Plug-Ins
- Using Frames with JavaScript
  - Objects for Frames
  - Using JavaScript in Multiframe Windows
- Creating a Framed Document
- Modifying the Navigation Bar
- Testing the Multiframe Document
- Updating a Frame with JavaScript
- Remembering User Preferences with Cookies
- Workshop Wrap-Up
  - Next Steps
  - Q&A

## Chapter 10 Working with Multiple Pages and Data

- Working with a Complex Web Site
- Creating an Application in Nested Framesets
- Working with Databases and Data
  - Using String Arrays
  - Using Associative Arrays
  - Creating Custom Data Structures
- Understanding Data Tainting
  - Enabling Data Tainting
  - Data Tainting Commands
- Working with Documents on Multiple Servers
- Maintaining State in JavaScript
- Creating a Questionnaire
- Workshop Wrap-Up
  - Next Steps
  - Q&A

## Chapter 11 Real-Life Examples II

- Example 1: Nonscrolling Status Line Messages
- Example 2: An Improved Navigation Bar
- Example 3: Storing User Preference

## Chapter 12 Working with Graphics in JavaScript

- Creating Graphical Back and Forward Buttons
- Using Dynamic Images in JavaScript
  - The `images` Array
  - Preloading Images
- Replacing Images Dynamically
- Creating a Graphical Clock
- Rotating Between Advertisement Banners
- JavaScript and Client-Side Image Maps
- Using an Image Map with JavaScript
- Workshop Wrap-Up
  - Next Steps
  - Q&A

## Chapter 13 Working with Multimedia and Plug-Ins

- Using Sound in JavaScript
  - Configuring a Sound Player
- Playing Sounds on Events
- Overview: Netscape Plug-Ins
- Plug-Ins and JavaScript
  - Objects Related to Plug-Ins
- Listing Plug-Ins
- Listing MIME Types
- Testing for a Plug-In
- Workshop Wrap-Up
  - Next Steps
  - Q&A

## Chapter 14 Debugging JavaScript Programs

- Common Errors in JavaScript Programming
  - Syntax Errors
  - Timing Problems
  - Variable Problems
  - Reserved Words
  - Platform-Specific Issues
- Techniques for Debugging
- Using Alerts to Display Values
- Debugging with a Temporary Window
- Tools for JavaScript Debugging
  - Using the JavaScript Command Line
- Testing JavaScript Commands Interactively
  - The JavaScript Trace Facility
- Installing the JavaScript Trace Facility
- Dealing with Bugs and Crashes
  - Netscape Navigator 2.0
  - Netscape Navigator 2.01
  - Netscape Navigator 2.02
  - Netscape Navigator 3.0 (Atlas)
  - Microsoft Internet Explorer
- Workshop Wrap-Up
  - Next Steps
  - Q&A

## Chapter 15 Real-Life Examples III

- Planning the Program
- The Complete Application
- How the Program Works
  - Initializing the Game
  - Placing Cards
  - Scoring the Game
  - Ending a Game

## Chapter 16 Integrating JavaScript with Java

- An Overview of Java
  - How Java Works
  - The Java Language
  - Java Objects and Classes
  - Integrating Java with HTML
  - Creating Your Own Java Applets
- Installing the Java Development Kit
- Creating a Simple Java Applet
- Compiling and Viewing a Java Applet
- Using Java Classes with JavaScript
  - Calling Java Methods
  - The `applet` Object
  - Making the Java Applet Accessible
- Controlling a Java Applet
- Calling JavaScript Functions from Java
  - Steps for the JavaScript Programmer
  - Steps for the Java Programmer
- Workshop Wrap-Up
  - Next Steps
  - Q&A

## Chapter 17 Combining JavaScript, CGI, and SSI

- Choosing the Right Tool for the Job
  - Comparing JavaScript with CGI
- The Basics of CGI
  - `GET` and `POST` Requests
  - Defining Requests in Forms
  - Name and Value Pairs
  - Environmental Variables
  - How CGI Programs Generate Output
- SSI: CGI Within a Web Page
  - Server-Side Include Directives
  - Enabling Server-Side Includes
- Languages for CGI and SSI
  - Perl
  - C and C++
  - Other Languages
- Creating a Simple CGI Program
- Installing a CGI Script
- Creating JavaScript Functions with SSI
- Workshop Wrap-Up
  - Next Steps
  - Q&A

## Chapter 18 Using ActiveX and Microsoft Internet Explorer 3.0

- Downloading and Installing Internet Explorer 3.0
- Internet Explorer and JavaScript
- Using ActiveX Controls
  - How ActiveX Controls Work
- Using an Existing ActiveX Control
  - A Sampling of ActiveX Controls and Features
- Using the ActiveX Control Pad
  - Developing ActiveX Controls
- An Introduction to VBScript
- Creating a Simple VBScript Application
- VBScript Versus JavaScript
  - Punctuation and Syntax
  - Variables
  - VBScript and Forms
  - Object-Oriented Features
  - ActiveX and VBScript
- Workshop Wrap-Up
  - Next Steps
  - Q&A

## Chapter 19 Real-Life Examples IV

- Example 1: Manipulating a Java Applet
- Example 2: Creating JavaScript Dynamically
- Example 3: Using an ActiveX Control

## Chapter 20 The Future of JavaScript

- Planned New Features
  - LiveConnect
- A JavaScript Wish List
  - Language Features
  - Interactive Forms
  - Graphics and Multimedia
  - User Interfaces and Frames
  - Java and Plug-Ins
- New Applications for JavaScript
- JavaScript Development Environments
- Alternatives to JavaScript
  - Java
  - CGI
  - SSI
  - LiveWire: Server-Side JavaScript
  - Shockwave
  - ActiveX
  - VBScript
  - HTML Enhancements
- Workshop Wrap-Up
  - Next Steps
  - Q&A
  - Conclusion

## appendix A JavaScript Structure and Objects Reference

- Built-In Objects
  - `Array`
  - `String`
  - `Math`
  - `Date`
  - `navigator`
- The JavaScript Object Hierarchy
  - `window`
  - `location`
  - `history`
  - `document`
- Creating and Customizing Objects
  - Creating Objects
  - Customizing Objects

## appendix B JavaScript Statements, Functions, Operators, and Keywords Reference

- JavaScript Statements
  - Comments
  - `break`
  - `continue`
  - `for`
  - `for...in`
  - `function`
  - `if...else`
  - `return`
  - `var`
  - `while`
- JavaScript Built-In Functions
  - `eval`
  - `parseInt`
  - `parseFloat`
  - `isNaN()`
  - `escape()`
  - `unescape()`
  - `taint()`
  - `untaint()`
- JavaScript Operators
- JavaScript Keywords

## appendix C Online JavaScript Resources

- JavaScript
  - Newsgroups and Mailing lists
  - Web Sites
- HTML and the Web in General
  - HTML Information
  - Browser Manufacturers
  - Other Sites
- Java
  - Sun's Java Site
  - Gamelan
  - The Java Man
  - JavaWorld
- Plug-Ins
  - Netscape's Plug-In Guide
  - Plug-In Plaza
  - Shockwave
  - Adobe's Acrobat
  - QuickTime
  - Live3d
  - ncompass
- CGI and SSI
  - ncSA's CGI Documentation
  - CGI FAQ
  - Tools for Aspiring Web Weavers
  - Perl Information
  - Newsgroups
- MSIE, ActiveX, and VBScript
  - Microsoft's Pages
  - JScript
  - The ActiveX Arena
- Miscellaneous Resources
  - VRML
  - GIF Animations
  - Web Security

## Credits

Copyright © 1996 by Sams.net Publishing

### FIRST EDITION

All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Neither is any liability assumed for damages resulting from the use of the information contained herein. For information, address Sams.net Publishing, 201 W. 103rd St., Indianapolis, IN 46290.

International Standard Book Number: 1-57521-141-6

HTML conversion by :
M/s. LeafWriters (India) Pvt. Ltd.
Website : http://leaf.stpn.soft.net
e-mail : leafwriters@leaf.stpn.soft.net

President, Sams Publishing: | Richard K. Swadley
Publishing Manager | Mark Taber
Managing Editor: | Cindy Morrow
Director of Marketing: | John Pierce
Assistant Marketing Managers: | Kristina Perry, Rachel Wolfe

Acquisitions Editor | Mark Taber | Development Editor | Fran Hatton
Software Development Specialist | Bob Correll | Production Editor | Nancy Albright
Indexer | Charlotte Clapp | Technical Reviewer | Jeff Shockley
Editorial Coordinator | Bill Whitmer | Technical Edit Coordinator | Lorraine Schaffer
Resource Coordinator | Deborah Frisby | Editorial Assistants | Carol Ackerman, Andi Richter, Rhonda Tinch-Mize
Cover Designer | Alyssa Yesh | Book Designer | Alyssa Yesh
Copy Writer | Peter Fuller | Production Team Supervisor | Brad Chinn
Production | Stephen Adams, Debra Bolhuis, Mona Brown, Bruce Clingaman, Jason Hand, Daniel Harris, Ayanna Lacey, Clint Lahnen, Laura Robbins, Susan Van Ness

### Acknowledgments

I'd like to thank everyone involved in the production of this book. Mark Taber at Sams.net helped fine-tune the initial proposal and got the project off the ground, and he's been involved at every stage. Mark always has time for my questions and has been a great help. Kelly Murdock and Fran Hatton were very helpful in fine-tuning the outline.

Fran also made many helpful comments in the editing stage. I'd like to thank the editor, Nancy Albright, for her comments and edits, which made things much more readable. Deborah Frisby helped to keep the editing process moving along.

I'd like to thank the Software Specialist for this book, Bob Correll, who was very helpful in putting together the content of the CD-ROM. I'd also like to thank the rest of the staff at Sams.net for their help in publishing this book.

Laura Lemay deserves mention for writing the great HTML books that launched the Web Workshop series.

Thanks to Netscape for giving me something to write about, and specifically to Brendan Eich, who goes above and beyond the call of duty in answering questions. I'd also like to thank all the participants in the JavaScript newsgroups and mailing lists; their answers helped me learn JavaScript, and their questions helped me know what to write about.

Finally, personal thanks go to my wife, Laura, my parents, Gary and Susan Moncur, the rest of my family, and my friends, particularly Chuck Perkins, Matt Strebe, Cory Storm, Robert Parsons, Dylan Winslow, James Chellis, Curt Siffert, and Henry J. Tillman. I couldn't have done it without your support.

### About the Author

Michael Moncur is the owner of Starling Technologies, a consulting firm specializing in networking and the Internet. He is also a freelance webmaster and author, and has worked with the Internet since 1989. He has written several bestselling books about Novell networks.

### Tell Us What You Think!

As a reader, you are the most important critic and commentator of our books. We value your opinion and want to know what we're doing right, what we could do better, what areas you'd like to see us publish in, and any other words of wisdom you're willing to pass our way. You can help us make strong books that meet your needs and give you the computer guidance you require.

Do you have access to CompuServe or the World Wide Web? Then check out our CompuServe forum by typing `GO SAMS` at any prompt. If you prefer the World Wide Web, check out our site at `http://www.mcp.com`.

Note
If you have a technical question about this book, call the technical support line at (800) 571-5840, ext. 3668.

As the team leader of the group that created this book, I welcome your comments. You can fax, e-mail, or write me directly to let me know what you did or didn't like about this book-as well as what we can do to make our books stronger. Here's the information:

FAX: | 317/581-4669
E-mail: | `newtech_mgr@sams.mcp.com`
Mail: | Mark Taber Sams Publishing 201 W. 103rd Street Indianapolis, IN 46290

### Introduction

The World Wide Web began as a simple repository for information, but it has grown into much more-it entertains, teaches, advertises, and communicates. As the Web has evolved, the tools have also evolved. Simple markup tools such as HTML have been joined by true programming languages-including JavaScript.

Now don't let the word "programming" scare you. For many, the term conjures up images of long nights staring at the screen, trying to remember which sequence of punctuation marks will produce the effect you need. (Don't get me wrong. Some of us enjoy that sort of thing-and that's fine too.)

Although JavaScript is programming, it's a very simple language. As a matter of fact, if you haven't programmed before, it makes a great introduction to programming. It requires very little knowledge to start programming with JavaScript-you'll write your first program in Chapter 1, "Creating Simple JavaScript Programs."

If you have programmed in other languages, you'll find JavaScript interesting-it's a language with very few solid rules. The syntax is easy to master, and programming with JavaScript can actually be fun. I've programmed in many languages, and I've found that I can write a truly useful, rewarding application in JavaScript in only an hour or two-with other languages, it often takes days before you see the first actual result of the program.

JavaScript can do all sorts of things to liven up Web pages, and you can even create entire applications that span multiple pages. This book covers them all-serious business applications, gadgets such as scrolling messages, and even games.

Of course, every language has its limitations, and JavaScript is no exception-if it could do everything, it wouldn't be easy to learn. Throughout this book I've pointed out the areas where JavaScript falls short. I also introduce the tools you can use to fill the gaps in JavaScript-CGI, SSI, and Java.

If you've spent much time developing pages for the Web, you know that the Web is constantly changing, and it can be hard to keep up with the latest features. This book will help you add JavaScript to your Web development toolbox, and I think you'll enjoy learning it.

I really had fun writing this book-and believe it or not, writing isn't always fun. I hope you'll have as much fun as you experiment with JavaScript and its capabilities.

### Who Should Read This Book

If you want to learn how to enhance your Web pages with JavaScript, this book is for you. I have made a few assumptions, though:

- You are familiar with the World Wide Web and the basics of creating Web pages with HTML.
- You have a 100-percent JavaScript-compatible browser handy-at the moment, that means the latest version of Netscape. If you don't, see appendix C, "Online JavaScript Resources," for the site from which to download it.
- Of course, you'll need a computer on which to run the browser. Netscape is available for Windows, Windows 95, Macintosh, and UNIX, and the examples in this book should work on any of those platforms. A few of the examples require graphics or other files on the CD-ROM accompanying this book.
- You'll also need a text editor-a simple one such as Windows Notepad will work fine.
- To view the examples online, you'll need a connection to the Internet, and you'll need a provider with a Web server to publish your pages. However, most of the examples in this book will work equally well offline.

Note
Although they're often confused, JavaScript and Java are very different languages. Although we introduce Java and explain how to connect it with JavaScript, this is primarily a book about JavaScript.

### How to Read This Book

This book is divided into six parts, roughly organized according to the complexity of their subjects:

- Part I, "Fast Track to JavaScript Programming," gives you a quick start with JavaScript programming, and introduces a few basic concepts.
- Part II, "Using JavaScript Objects and Forms," explains objects and forms-the foundations of building JavaScript applications.
- Part III, "Creating Smart Web Pages," looks at some of the more complicated issues of JavaScript, with a focus on adding intelligent, interactive features to your Web pages.
- Part IV, "Advanced JavaScript Concepts," includes more advanced concepts, including graphics, multimedia, and debugging.
- Part V, "JavaScript Alternatives and the Future," examines some of the other popular Web languages and explains how they can be combined with JavaScript in your pages. The last chapter looks at the changes and other issues that may affect JavaScript programming in the future.
- Part VI includes four appendixes. These give a concise reference for JavaScript and a list of online resources.

Although this book is organized so that it can be read from cover to cover, you don't need to. You'll want to read Chapter 1 to understand the basic concepts of JavaScript, but you can then skip around as you please. At the end of each chapter you'll find a list of next steps-other chapters to continue your learning, not necessarily in order.

Throughout this book you'll find Tasks, which show you how to use a particular JavaScript feature and include a working example application. The applications range from simple gadgets to business applications to games and graphics.

## A Note About Software

JavaScript-like most Web-related languages and products-is constantly evolving. As it has grown in popularity, features have been added and changes have been made. Because of this, which browser you use can affect how well things work.

The examples in this book were developed with Netscape 3.0, and have all been tested on the final version of 3.0. Where possible, I've made every effort to ensure that they'll work on earlier versions, but I recommend that you download the latest version to be sure everything will work.

You may also run into problems if you use a newer browser-needless to say, I wasn't able to test the examples on programs that didn't exist at this writing. Don't download an earlier version, though-my recommendation is to keep the latest version, but consult this book's Web site (see address later in this Introduction) to find out how things have changed.

## Keeping in Touch

I can't update your copy of this book each time JavaScript changes, but I've done the next best thing. I've set up a Web site devoted to this book. Here's the URL:

>     http://www.starlingtech.com/books/javascript/

At this site, you'll find online versions of all the examples in this book and a variety of additional examples demonstrating JavaScript's features. You will also find information about the latest new JavaScript features and how you can adapt the examples or your own programs to use them.

If you have any questions or comments about this book and its content, check the Web site for additional information. If you don't find what you need there, feel free to contact me directly via e-mail at this address:

>     jsbooks@starlingtech.com

If you have trouble getting one of the programs in this book to work, or with your own programs, first check out the online resources in appendix C. If that doesn't help, feel free to contact me and I'll try to help; be warned, though, that it may take me a week or two to dig myself out from my current pile of e-mail to reply.

Last but not least, if you've created a JavaScript application that you're proud of, I'd like to see it. Send the URL to the e-mail address above. I'll post links to some of the best applications created by readers on the Web site.